package cn.globalph.housekeeper.utils.lifecycle

import android.Manifest
import android.annotation.SuppressLint
import android.app.*
import android.content.Context
import android.util.Log
import androidx.appcompat.app.AlertDialog
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions
import cn.globalph.housekeeper.ui.main.MainActivity
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import cn.globalph.housekeeper.R


const val LOCATION_PERMISSION = 1211
class LocationObserver :EasyPermissions.PermissionCallbacks{


    private val locationPermissions =
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_BACKGROUND_LOCATION)
        }else{
            arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION)
        }


    private var mLocationClient:LocationClient? = null
    private var myLocationConfiguration = MyLocationListener()
    private var mActivity:Activity

    var locationListener:LocationListener? = null

    constructor(activity: Activity){
        mActivity = activity
        mLocationClient = LocationClient(mActivity.application)
        mLocationClient?.registerLocationListener(myLocationConfiguration)
        setOption()
        notifycation()
    }

    private fun setOption(){
        val option = LocationClientOption()

        option.locationMode = LocationClientOption.LocationMode.Hight_Accuracy
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll")
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(1000)
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.isOpenGps = true
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true

        option.isLocationNotify = true
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false)
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false)
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000)
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false)
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient?.locOption = option
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明
    }

    var channelId = "111"
    private fun notifycation(){
        //开启前台定位服务：

        val builder = NotificationCompat.Builder(mActivity.applicationContext,channelId)

        var notificationManager = mActivity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "housekeeper", NotificationManager.IMPORTANCE_DEFAULT
            )
            channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE//设置是否应在锁定屏幕上显示此频道的通知
            channel.description = "品荟管家"//设置渠道描述
            notificationManager?.createNotificationChannel(channel)
        }

//获取一个Notification构造器

        val nfIntent = Intent(mActivity.applicationContext, MainActivity::class.java)
        builder.setContentIntent(
            PendingIntent.getActivity(
                mActivity.applicationContext,
                0,
                nfIntent,
                0
            )
        ) // 设置PendingIntent
            .setContentTitle("正在进行后台定位") // 设置下拉列表里的标题
            .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
            .setContentText("后台定位通知") // 设置上下文内容
            .setAutoCancel(true)
            .setWhen(System.currentTimeMillis()) // 设置该通知发生的时间
        var notification: Notification? = null
        notification = builder.build()
        notification!!.defaults = Notification.DEFAULT_SOUND //设置为默认的声音
        mLocationClient?.enableLocInForeground(1001, notification)// 调起前台定位
    }

    @AfterPermissionGranted(LOCATION_PERMISSION)
    fun start(){
        if(EasyPermissions.hasPermissions(mActivity, *locationPermissions)){
            mLocationClient?.start()
        }else{
            EasyPermissions.requestPermissions(mActivity,"获取位置需要定位权限",LOCATION_PERMISSION,*locationPermissions)
        }
    }


    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        if (requestCode == LOCATION_PERMISSION) {
            for(i in 0 until perms.size){
                Log.i("location",perms[i])
            }

            if(perms.size == 1
                && perms[0] == "android.permission.ACCESS_BACKGROUND_LOCATION"
                && Build.VERSION.SDK_INT<Build.VERSION_CODES.Q){
                return
            }
            locationListener?.onPermissionDeney()
//            AlertDialog.Builder(mActivity)
//                .setTitle(R.string.tip)
//                .setMessage(R.string.permission_location_denied)
//                .setPositiveButton(R.string.ensure
//                ) { dialogInterface, _ -> dialogInterface.dismiss() }
//                .show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    inner class MyLocationListener:BDAbstractLocationListener(){
        override fun onReceiveLocation(location: BDLocation) {
            val latitude = location.latitude    //获取纬度信息
            val longitude = location.longitude    //获取经度信息

            Log.i("latlong","$latitude $longitude")
            val radius = location.radius    //获取定位精度，默认值为0.0f

            val coorType = location.coorType
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            val errorCode = location.locType
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            mLocationClient?.stop()
            locationListener?.onReceiveLocation(latitude,longitude)
        }
    }

    interface LocationListener{
        fun onReceiveLocation(lat:Double,lon:Double)
        fun onPermissionDeney()
    }
}